<template>
  <div class="app-container">
    <!-- <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="" prop="deptName"> </el-form-item>
      <el-form-item label="" prop="status"> </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->
    <div class="container-search">
      <div class="search">
        <div class="search-item">
          <el-input
            v-model="queryParams.deptName"
            placeholder="请输入部门名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </div>
        <div class="search-item">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择部门状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-button type="primary" @click="handleQuery"
            ><img src="@/assets/images/search.png" alt="" /> 搜索</el-button
          >
          <el-button color="#eff3ff" :dark="true" @click="resetQuery"
            ><img src="@/assets/images/reset.png" alt="" />
            <span style="color: #6d98fd">重置 </span>
          </el-button>
        </div>
      </div>
    </div>
    <!-- 
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
         
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <div class="container-button">
      <el-button
        type="primary"
        @click="handleAdd"
        v-hasPermi="['system:dept:add']"
        ><img src="@/assets/images/add.png" alt="" />新增</el-button
      >
    </div>
    <div class="container-table">
      <el-table
        v-if="refreshTable"
        v-loading="loading"
        border
        :data="deptList"
        row-key="deptId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        height="68vh"
      >
        <el-table-column prop="deptName" label="组织名称"></el-table-column>
        <el-table-column
          prop="orderNum"
          label="排序"
          width="100"
        ></el-table-column>
        <el-table-column prop="deptTypeName" label="类型" width="200">
        </el-table-column>
        <el-table-column prop="areaName" label="行政区划" width="200">
        </el-table-column>
        <el-table-column prop="deptCount" label="组织人数" width="100">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          width="180"
          :resizable="false"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <span
                class="edit"
                @click="handleUpdate(row)"
                v-hasPermi="['system:dept:edit']"
                >修改</span
              >
              <span
                class="detail"
                @click="handleAdd(row)"
                v-hasPermi="['system:dept:add']"
                v-if="[0, 1].includes(row.deptType)"
                >新增</span
              >
              <span
                class="delete"
                @click="handleDelete(row)"
                v-hasPermi="['system:dept:remove']"
                >删除</span
              >
            </div>
            <!-- <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:dept:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Plus"
              @click="handleAdd(scope.row)"
              v-hasPermi="['system:dept:add']"
              >新增</el-button
            >
            <el-button
              v-if="scope.row.parentId != 0"
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:dept:remove']"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加或修改部门对话框 -->
    <el-dialog v-model="open" width="1000px" append-to-body>
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <img src="@/assets/images/title-card.png" alt="" />
          <div class="header-title">{{ title }}</div>
        </div>
      </template>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="deptOptions"
                :props="{
                  value: 'deptId',
                  label: 'deptName',
                  children: 'children',
                }"
                style="width: 100%"
                value-key="deptId"
                placeholder="选择上级部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input
                v-model="form.leader"
                placeholder="请输入负责人"
                maxlength="20"
              />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系电话"
                maxlength="11"
              />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织类型" prop="deptType">
              <el-select
                v-model="form.deptType"
                placeholder="请选择组织类型"
                clearable
                style="width: 100%"
                @change="clearregion"
              >
                <el-option
                  v-for="dict in typeList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue * 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政区划" prop="region">
              <el-cascader
                v-if="form.deptType == 1"
                v-model="form.region"
                placeholder="请选择行政区划"
                :options="options"
                filterable
                clearable
                @change="handlerregion"
                :props="streetareaprops"
                style="width: 100%"
              />
              <el-cascader
                v-else
                v-model="form.region"
                placeholder="请选择行政区划"
                :options="options"
                filterable
                clearable
                @change="handlerregion"
                :props="areaprops"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.deptType == 2">
            <el-form-item label="管理行业" prop="industryManagementId">
              <el-select
                v-model="form.industryManagementId"
                placeholder="请选择组织类型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in industryList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue * 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dept">
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
} from "@/api/system/dept";
import { getDictsApi, getAreaList } from "@/api/dict";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const deptList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);
const typeList = ref([]);
const industryList = ref([]);
let options = ref([]);

const areaprops = {
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    let datas = [];
    setTimeout(() => {
      let code = 1;
      if (level != 0) {
        code = node.data.value;
      }
      getAreaList({ pid: code }).then((response) => {
        if (response.data && response.data.length) {
          datas = response.data.map((item, i) => ({
            value: item.value,
            label: item.label,
            leaf: level >= 2,
            // disabled: level == 0, // 这里可以设置为 true 来禁用这个选项
          }));
        } else {
          datas = [];
        }
        resolve(datas);
      });
    }, 200);
  },
};

const streetareaprops = {
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    let datas = [];
    setTimeout(() => {
      let code = 1;
      if (level != 0) {
        code = node.data.value;
      }
      getAreaList({ pid: code }).then((response) => {
        if (response.data && response.data.length) {
          datas = response.data.map((item, i) => ({
            value: item.value,
            label: item.label,
            leaf: level >= 3,
            // disabled: level == 0, // 这里可以设置为 true 来禁用这个选项
          }));
        } else {
          datas = [];
        }
        resolve(datas);
      });
    }, 200);
  },
};

const clearregion = () => {
  form.value.region = [];
};

const provinceValidate = (rule, value, callback) => {
  const { region } = form.value;
  if (region.length == 0) {
    callback(new Error("请选择行政区划"));
  } else {
    callback();
  }
};

const data = reactive({
  form: {
    region: [],
  },
  queryParams: {
    deptName: undefined,
    status: undefined,
  },
  rules: {
    parentId: [
      { required: true, message: "上级部门不能为空", trigger: "blur" },
    ],
    deptName: [
      { required: true, message: "部门名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "显示排序不能为空", trigger: "blur" },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    deptType: [
      {
        required: true,
        message: "请选择组织类型",
        trigger: ["change"],
      },
    ],
    region: [
      {
        required: true,
        validator: provinceValidate,
        trigger: "change",
      },
    ],
    industryManagementId: [
      {
        required: true,
        message: "请选择管理行业",
        trigger: ["change"],
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询部门列表 */
function getList() {
  loading.value = true;
  listDept(queryParams.value).then((response) => {
    deptList.value = proxy.handleTree(response.data, "deptId");
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "0",
    region: [],
  };
  proxy.resetForm("deptRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  // proxy.resetForm("queryRef");
  queryParams.value = {
    deptName: undefined,
    status: undefined,
  };
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  listDept().then((response) => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  if (row != undefined) {
    form.value.parentId = row.deptId;
  }
  open.value = true;
  title.value = "添加组织";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  listDeptExcludeChild(row.deptId).then((response) => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  getDept(row.deptId).then((response) => {
    form.value = response.data;
    form.value.region = [];
    form.value.provinceId && form.value.region.push(form.value.provinceId);
    form.value.cityId && form.value.region.push(form.value.cityId);
    form.value.zoneId && form.value.region.push(form.value.zoneId);
    form.value.streetId && form.value.region.push(form.value.streetId);
    console.log("response.data", response.data);
    open.value = true;
    title.value = "修改部门";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.deptName + '"的数据项?')
    .then(function () {
      return delDept(row.deptId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/**
 * @description: 联级处理省市区操作
 * @param {String} type 类型
 */
const handlerregion = (value) => {
  if (value) {
    form.value.provinceId = value[0];
    form.value.cityId = value[1];
    form.value.zoneId = value[2];
    form.value.streetId = value[3];
  } else {
    form.value.region = [];
    form.value.provinceId = null;
    form.value.cityId = null;
    form.value.zoneId = null;
    form.value.streetId = null;
  }
};
/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("fkwz_organizational_type").then((res) => {
    // 审核状态
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });
  await getDictsApi("institution_industry_type").then((res) => {
    // 审核状态
    if (res.code === 200) {
      industryList.value = res.data;
    }
  });
}
getList();
getDicts();
</script>

<style scoped lang="scss">
.container-search {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 15px 15px 15px 15px;
}
.container-button {
  position: absolute;
  top: 15px;
  right: 15px;
  img {
    margin-right: 6px;
    margin-top: 2px;
  }
}
.container-table {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 15px 15px 15px 15px;
  margin-top: 30px;
  .sort {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 15px;
    .sort-title {
      font-size: 14px;
    }
  }
}
</style>
